import {
  Component,
  OnInit,
  ViewEncapsulation,
  ChangeDetectionStrategy,
  OnChanges,
  EventEmitter,
  AfterViewInit,
  ViewChild,
  ViewContainerRef,
  ComponentRef,
  CompilerFactory,
  Compiler,
  OnDestroy
} from '@angular/core';
import { QuoteHeader } from "quote";

@Component({
  // moduleId: module.id,
  selector: 'quote-table-cell',
  templateUrl: 'quote-table-cell.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush,
  encapsulation: ViewEncapsulation.None,
  inputs: [
    "cell",
    "header",
    "isHeader",
    "quote"
  ],
  outputs: [
    "headerClick"
  ]
})
export class QuoteTableCellComponent implements OnInit, OnChanges, AfterViewInit, OnDestroy {
  headerClick = new EventEmitter();
  isHeader;
  header;
  quote;
  currentSort;
  wasViewInitialized;
  @ViewChild("appendContainer", { read: ViewContainerRef })
  appendContainer: ViewContainerRef;
  appendComponentRef: ComponentRef<any>;

  constructor(private compiler: Compiler) { }

  ngOnInit() {

  }

  ngOnChanges(changes) {
    // if (this.wasViewInitialized) {
    //   return;
    // }
    // this.refreshContent();
  }

  ngAfterViewInit() {
    this.wasViewInitialized = true;
    this.refreshContent();
  }

  ngOnDestroy() {
    if (this.appendComponentRef) {
      this.appendComponentRef.destroy();
      this.appendComponentRef = null;
    }

  }

  getValue(value) {
    let float = parseFloat(value);
    return isNaN(float) ? value : float.toFixed(2);
  }

  onClick(header) {
    this.headerClick.emit(header);
  }

  refreshContent() {
    if (!this.header.appendModule) return;
    if (this.appendComponentRef) {
      this.appendComponentRef.destroy();
      this.appendComponentRef = null;
    }
    let factory;
    let appendModule = this.header.appendModule;
    let { isHeader, compiler, appendContainer } = this;
    let componentName = isHeader ? appendModule["headerComponentName"] : appendModule["cellComponentName"];
    compiler // 就用promise吧，懒
      .compileModuleAndAllComponentsAsync(appendModule.module)
      .then(moduleWithFactories => moduleWithFactories.componentFactories)
      .then(componentFactories =>
        componentFactories.filter(
          factory => factory.componentType.name === componentName))
      .then(factories => factories.length ? factories.reduce(first => first) : null)
      .then(factory => {
        this.appendComponentRef = this.appendContainer.createComponent(factory);
        this.appendComponentRef.instance.stock = this.quote;
        // console.debug("Component: ", factory);
      })
  }


}